<template>
  <view class="page">
    <!-- 待配送订单列表 -->
    <scroll-view class="order-list" scroll-y lower-threshold="60" @scrolltolower="loadMore">
      <view class="order-item" v-for="order in orderList" :key="order.id">
        <view class="order-header">
          <text class="order-no">订单号：{{ order.orderNo }}</text>
          <text class="order-time">{{ order.acceptTime }}</text>
        </view>

        <!-- 配送地址 -->
        <view class="address-card">
          <view class="address-icon">📍</view>
          <view class="address-content">
            <view class="address-info">
              <text class="contact-name">{{ order.contactName || '用户' }}</text>
              <text class="contact-phone">{{ order.contactPhone || order.deliveryAddress }}</text>
            </view>
            <text class="address-text">{{ order.deliveryAddress }}</text>
          </view>
        </view>

        <!-- 订单商品摘要 -->
        <view class="goods-summary">
          <text class="summary-text">{{ getOrderSummary(order) }}</text>
          <text class="order-amount">¥{{ order.actualAmount }}</text>
        </view>

        <!-- 操作按钮 -->
        <view class="order-actions">
          <view class="btn-action" @click="callUser(order)">
            <text class="action-icon">📞</text>
            <text>联系用户</text>
          </view>
          <view class="btn-action" @click="viewDetail(order)">
            <text class="action-icon">📋</text>
            <text>查看详情</text>
          </view>
          <view class="btn-action primary" @click="completeDelivery(order)">
            <text class="action-icon">✅</text>
            <text>送达</text>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty" v-if="hasLoaded && orderList.length === 0 && !loading">
        <text class="empty-icon">📦</text>
        <text class="empty-text">暂无待配送订单</text>
        <text class="empty-subtext">{{ emptyTips }}</text>
      </view>

      <!-- 加载更多 -->
      <view class="loadmore" v-if="orderList.length > 0">
        <text class="loadmore-text">{{ loadingText }}</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderList: [],
      page: 1,
      pageSize: 20,
      loading: false,
      finished: false,
      hasLoaded: false,
      emptyTips: '可以稍后再来看看，或下拉刷新以获取最新订单~'
    }
  },
  computed: {
    loadingText() {
      if (this.loading) return '加载中...'
      if (this.finished) return '没有更多了'
      return '上拉加载更多'
    }
  },
  onLoad() {
    this.loadOrders()
  },
  onShow() {
    // 刷新列表
    this.page = 1
    this.finished = false
    this.orderList = []
    this.hasLoaded = false
    this.loadOrders()
  },
  onPullDownRefresh() {
    this.page = 1
    this.finished = false
    this.orderList = []
    this.hasLoaded = false
    this.loadOrders()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 1000)
  },
  methods: {
    async loadOrders() {
      if (this.loading || this.finished) return
      
      this.loading = true
      
      try {
        const { getOrderPage } = require('@/api/order')
        
        // 查询配送中的订单
        const pageData = await getOrderPage({
          status: 3,
          orderType: 1,
          current: this.page,
          size: this.pageSize
        })
        
        const records = pageData.records || []
        
        if (this.page === 1) {
          this.orderList = records
        } else {
          this.orderList.push(...records)
        }
        
        this.loading = false
        this.hasLoaded = true
        
        if (records.length < this.pageSize || this.page >= (pageData.pages || 1)) {
          this.finished = true
        }
      } catch (error) {
        console.error('加载订单失败:', error)
        this.loading = false
        this.hasLoaded = true
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },
    
    loadMore() {
      if (this.loading || this.finished) return
      this.page++
      this.loadOrders()
    },
    
    getOrderSummary(order) {
      if (order.items && order.items.length > 0) {
        const firstItem = order.items[0]
        const moreCount = order.items.length - 1
        return moreCount > 0 
          ? `${firstItem.productName} 等${order.items.length}件商品`
          : firstItem.productName
      }
      return '订单详情'
    },
    
    callUser(order) {
      if (!order.contactPhone) {
        uni.showToast({
          title: '暂无联系方式',
          icon: 'none'
        })
        return
      }
      
      uni.showActionSheet({
        itemList: [`拨打电话: ${order.contactPhone}`, '复制手机号'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 拨打电话
            uni.makePhoneCall({ 
              phoneNumber: order.contactPhone 
            })
          } else if (res.tapIndex === 1) {
            // 复制手机号
            uni.setClipboardData({ 
              data: order.contactPhone,
              success: () => {
                uni.showToast({
                  title: '手机号已复制',
                  icon: 'success'
                })
              }
            })
          }
        }
      })
    },
    
    viewDetail(order) {
      uni.navigateTo({
        url: `/pages/order/detail?id=${order.id}`
      })
    },
    
    completeDelivery(order) {
      uni.showModal({
        title: '确认送达',
        content: '确认已将商品送达并完成该订单？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '提交中...' })
              const { finishOrder } = require('@/api/order')
              await finishOrder(order.id)
              uni.hideLoading()
              uni.showToast({
                title: '订单已完成',
                icon: 'success'
              })
            
              // 刷新列表
              setTimeout(() => {
                this.page = 1
                this.finished = false
                this.orderList = []
                this.hasLoaded = false
                this.loadOrders()
              }, 1200)
            } catch (error) {
              console.error('完成订单失败:', error)
              uni.hideLoading()
              uni.showToast({
                title: error.message || '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.order-list {
  flex: 1;
  height: 100%;
  padding: 20rpx;
}

.order-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .order-no {
    font-size: 24rpx;
    color: #999;
  }
  
  .order-time {
    font-size: 24rpx;
    color: #999;
  }
}

.address-card {
  display: flex;
  gap: 16rpx;
  padding: 24rpx 0;
  
  .address-icon {
    font-size: 40rpx;
    line-height: 1;
  }
  
  .address-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 12rpx;
  }
  
  .address-info {
    display: flex;
    gap: 20rpx;
    
    .contact-name {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
    
    .contact-phone {
      font-size: 28rpx;
      color: #667eea;
    }
  }
  
  .address-text {
    font-size: 26rpx;
    color: #666;
    line-height: 1.6;
  }
}

.goods-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-top: 1rpx solid #f0f0f0;
  
  .summary-text {
    flex: 1;
    font-size: 26rpx;
    color: #666;
  }
  
  .order-amount {
    font-size: 32rpx;
    font-weight: bold;
    color: #ff6b6b;
  }
}

.order-actions {
  display: flex;
  gap: 16rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.btn-action {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 20rpx 8rpx;
  background: #f5f7fa;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #666;
  
  &.primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
  }
  
  .action-icon {
    font-size: 28rpx;
  }
}

.empty {
  padding: 120rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 32rpx;
  
  .empty-icon {
    font-size: 160rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }

  .empty-subtext {
    font-size: 24rpx;
    color: #bbb;
  }
}

.loadmore {
  padding: 40rpx 20rpx;
  text-align: center;
  
  .loadmore-text {
    font-size: 24rpx;
    color: #999;
  }
}
</style>

